package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 支付成功通知消息监听器
 */
@Component
@Slf4j
public class OrderPayNotifyListener {

    @Autowired
    private OrderService orderService;

    /**
     * 监听订单支付结果消息
     *
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "order_pay_normal_queue")
    public void OrderPayNotify(Channel channel, Message message) {
        //1 获取消息内容
        byte[] body = message.getBody();
        String messageBodyJsonString = new String(body);

//        System.out.println(messageBodyMap);

        //2 手动确认消息
        //获取消息对象的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            //3 调用业务层方法，修改订单状态
            orderService.update(messageBodyJsonString);

            //确认消息
            channel.basicAck(deliveryTag, false);

        } catch (Exception e) {
            e.printStackTrace();
            try {
                //4 处理异常
                if (messageProperties.getRedelivered()) {
                    //消息两次确认失败
                    channel.basicReject(deliveryTag, false);
                    log.error("连续两次修改订单的支付结果都失败,支付报文为:" + messageBodyJsonString);
                } else {
                    //在试一次
                    channel.basicReject(deliveryTag, true);
                }
            } catch (Exception e1) {
                e1.printStackTrace();
                log.error("拒绝消息发生异常,修改订单可能失败了,需要确认,支付报文为:" + messageBodyJsonString);
            }
        }
    }
}
